import axios from "@/axios/axios"
import MUTATIONS from "./mutations";
import {getSession, setSession} from "@/util/session"

const state = () => {
  return {
    subject: [],
    queBank: [],
    history: getSession('history') || null,
    curHistoryInfo: getSession('curHistoryInfo') || {}
  }
}
const getters = {
  getQueBankInfo(state) {
    return (queBankId) => {
      if (!queBankId) return {
        subName: state.curHistoryInfo.COURSE_NAME,
        queBankName: state.curHistoryInfo.TK_NAME
      }
      return state.queBank.reduce((names, item) => {
        const {ID, COURSE_NAME, TK_NAME} = item
        if (ID === queBankId) {
          names.subName = COURSE_NAME;
          names.queBankName = TK_NAME
        }
        return names;
      }, {})
    }
  }
}
const mutations = {
  [MUTATIONS.SET_SUBJECT](state, subject) {
    state.subject = subject
  },
  [MUTATIONS.SET_QUE_BANK](state, queBank) {
    state.queBank = queBank
  },
  [MUTATIONS.EMPTY_QUE_BANK](state) {
    state.queBank = []
  },
  [MUTATIONS.SET_HISTORY](state, history) {
    state.history = history
    setSession('history', history)
  },
  [MUTATIONS.SET_CUR_HISTORY](state, curHistoryInfo) {
    state.curHistoryInfo = curHistoryInfo
    setSession('curHistoryInfo', curHistoryInfo)
  }
}
const actions = {
  getSubject({commit}) {
    return new Promise((resolve, reject) => {
      axios.post('subject.php').then((res) => {
        commit(MUTATIONS.SET_SUBJECT, res)
        resolve()
      }).catch(reject)
    })
  },
  getQueBank({commit}, ID) {
    commit(MUTATIONS.EMPTY_QUE_BANK)
    return new Promise((resolve, reject) => {
      axios.post("testpaper.php", {ID}).then((res) => {
        commit(MUTATIONS.SET_QUE_BANK, res)
        resolve()
      }).catch(reject)
    })
  },
  getHistory({commit}) {
    return new Promise((resolve, reject) => {
      axios.post('history.php').then((res) => {
        commit(MUTATIONS.SET_HISTORY, res.data.data)
        resolve()
      }).catch(reject)
    })
  },
  getTopicHistory({commit, dispatch}, history) {
    return new Promise((resolve, reject) => {
      axios.post("history_item.php", {ID: history.ID}).then((res) => {
        commit(MUTATIONS.SET_TOPIC, JSON.parse(res.data[0].HISTORY_DATA))
        commit(MUTATIONS.SET_CUR_HISTORY, res.data[0])
        res.jianda.length && dispatch('markJDAnswer', res.jianda)
        resolve()
      }).catch(reject)
    })
  }
}
export default {
  state,
  actions,
  getters,
  mutations
}
